#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/14 12:52
# @Author  : leon yan
# @Site    :
# @File    : ReportLog.py
# @Software: PyCharm

from PyQt5.QtCore import pyqtSlot, QFile, QIODevice, QTextStream, Qt, QDir, QFileInfo
from PyQt5.QtWidgets import (QApplication, QMainWindow, QMessageBox, QListWidgetItem, QFileDialog)

from resource.ReportLog_ui import Ui_QWFormTable


class QReportLog(QMainWindow, Ui_QWFormTable):

    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        # gl.init() # 调试用
        self.catalogType = {}
        self.label.setText("")
        self._FlagEditable = (Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsEditable)
        self._FlagNotEditable = (Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
        self.logDir = r"./log/log.log"
        self.readLog()

    def __del__(self):  # 析构函数
        print("ReportLog is deleted")

    def readLog(self):
        fileInfo = QFileInfo(self.logDir)
        parDir = fileInfo.absoluteFilePath()
        self.label.setText(parDir)
        curFile = self.logDir
        fileDevice = QFile(curFile)
        if not fileDevice.exists():
            QMessageBox.warning(self, "Tips", "FileNotFound!")
            # return
        if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
            return False
        '''逐行读取方式，可行'''
        '''用流方式读取'''
        try:
            lineStr = ""
            fileStream = QTextStream(fileDevice)
            fileStream.setAutoDetectUnicode(True)  # 自动检测Unicode
            # fileStream.setCodec("utf-8")  # 必须设置编码,否则不能正常显示汉字
            fileStream.setCodec("")
            self.listWidget.clear()
            self.plainTextEdit.clear()
            self.catalogType.clear()
            while not fileStream.atEnd():
                lineStr = fileStream.readLine()    # 读取文件的一行,读取出来就是str
                self.catalog(lineStr.split("T")[0], lineStr)
        finally:
            fileDevice.close()  # 关闭文件
        '''左侧目录'''
        self.createCatalog()

        if lineStr:
            self.plainTextEdit.clear()
            aa = sorted(self.catalogType.keys())[0]
            self.plainTextEdit.appendPlainText(self.catalogType[aa])  # 添加到文本框显示

    def catalog(self, strDate, strContext):
        if str(strDate) not in self.catalogType.keys():
            self.catalogType[str(strDate)] = strContext
        else:
            self.catalogType[str(strDate)] += "\n" + strContext

    def createCatalog(self):
        for key in self.catalogType.keys():
            itemStr = key
            aItem = QListWidgetItem()
            aItem.setText(itemStr)
            # aItem.setIcon(self.icon)
            # aItem.setCheckState(Qt.Unchecked)
            aItem.setFlags(self._FlagNotEditable)
            self.listWidget.addItem(aItem)

    def on_listWidget_currentItemChanged(self, current, previous):  # 当前项切换变化
        if current is not None:
            self.plainTextEdit.clear()
            self.plainTextEdit.appendPlainText(self.catalogType[current.text()])

    @pyqtSlot()
    def on_action_Save_As_triggered(self):
        curPath = QDir.currentPath()  # 获取系统当前目录
        title = "Save as file"  # 对话框标题
        filt = "log files(*.log);; All files(*.*)"  # 文件过滤器
        fileName, flt = QFileDialog.getSaveFileName(self, title, curPath, filt)
        if fileName == "":
            return
        if self._saveByStream(fileName):
            fileInfo = QFileInfo(fileName)
            parDir = fileInfo.filePath()
            self.label.setText(parDir)
        else:
            QMessageBox.critical(self, "Error", "Save failed")

    def _saveByStream(self, fileName):  # 用 QTextStream 保存文件
        fileDevice = QFile(fileName)
        if not fileDevice.open(QIODevice.WriteOnly | QIODevice.Text):
            return False
        try:
            fileStream = QTextStream(fileDevice)  # 用文本流读取文件
            fileStream.setAutoDetectUnicode(True)  # 自动检测Unicode
            # fileStream.setCodec("utf-8")  # 必须设置编码,否则不能正常显示汉字
            fileStream.setCodec("")
            text = self.plainTextEdit.toPlainText()  # 返回是str类型
            fileStream << text  # 使用流操作符
        # fileStream<<"\n***************在尾部添加的第1行"
        finally:
            fileDevice.close()
        return True

    @pyqtSlot()
    def on_actionClearLog_triggered(self):
        ret = QMessageBox.question(self, "Tips", "Are you sure you want to clear the log?\n(All logs will be cleared)")
        if ret != QMessageBox.Yes:
            return
        self.plainTextEdit.clear()
        self.listWidget.clear()
        self.delFile()
        # self._saveByStream(self.logDir)

    def delFile(self):
        fileInfo = QFileInfo(self.logDir)
        parDir = fileInfo.path()
        sour = fileInfo.baseName() + "." + fileInfo.suffix()
        dirobj = QDir(parDir)
        if dirobj.remove(sour):
            text = "ok"
        else:
            text = None
        return text

    @pyqtSlot()
    def on_action_Open_Log_triggered(self):
        sous = r"./log/log.log"
        try:
            if sous:
                curPath = sous
            else:
                curPath = QDir.currentPath()  # 获取系统当前目录
            filename, flt = QFileDialog.getOpenFileName(self, "Open a log file", curPath, "log(*.log)")
            if filename:
                self.logDir = filename
                self.readLog()
                # print(filename)
        except BaseException as e:
            print(e)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    objWindow = QReportLog()

    objWindow.show()
    sys.exit(app.exec_())
